package com.lv.suyiyong.hfrwork.ui

import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DesUtil
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.TimerUnit
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.bean.UserInfoOld
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.CompanyReqBody
import com.lv.service.net.SendCodeBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.XmlUtils
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.databinding.ActivityChangePasswordBinding
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：修改密码
 */
@Route(path = ARoutUtils.ChangePasswordActivity)
class ChangePasswordActivity : BaseActivity<ActivityChangePasswordBinding>(),
    View.OnClickListener {
    @Autowired(name = "userinfo")
    @JvmField
    var mUserInfo: UserInfo? = null

    @Autowired(name = "companyInfo")
    @JvmField
    var mCompanyInfo: CompanyItemBean? = null
    private var timer: TimerUnit? = null
    private var isShowPassWordTop: Boolean = false
    private var isShowPassWordBottom: Boolean = false
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_change_password
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@ChangePasswordActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("修改密码")
            ivEyes.setOnClickListener(this@ChangePasswordActivity)
            ivEyesP.setOnClickListener(this@ChangePasswordActivity)
            tvCode.setOnClickListener(this@ChangePasswordActivity)
            btnLogin.setSafeListener {
                val password = mEditorViewModel.obName.get()
                val password_ = mEditorViewModel.obCpname.get()
                if (password != password_) {
                    showToast("输入的密码不一致")
                } else {
                    val code = etCode.text.toString().trim()
                    lifecycleScope.launchWhenCreated {
                        this.launch {
                            if (mUserInfo != null) {
                                val result: DataResult<BaseYgxRsp> =
                                    myScope.async {
                                        val partMap = mutableMapOf<String, RequestBody>()
                                        partMap["password"] =
                                            YgxNetUtilsKt.partToRequestBody(
                                                DesUtil.encode(password) ?: ""
                                            )
//                                        partMap["phone"] = YgxNetUtilsKt.partToRequestBody(mUserInfo?.phone?:"")
                                        partMap["checkCode"] = YgxNetUtilsKt.partToRequestBody(code)
                                        serviceViewModel.updateMyMessage(
                                            partMap
                                        )

                                    }.await()
                                parseResult(result)
                            } else {
                                val result: DataResult<BaseYgxRsp> =
                                    myScope.async {
                                        serviceViewModel.updatePasswordOrPhone(
                                            CompanyReqBody(
                                                mCompanyInfo?.id ?: "",
                                                DesUtil.encode(password) ?: "",
                                                mCompanyInfo?.phone ?: "",
                                                code
                                            )
                                        )
                                    }.await()
                                parseCompanyResult(result)
                            }


                        }
                    }

                }

            }
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfoOld> { code, data, message, result ->
                if (code == "200") {

                    message?.let { message ->
                        showToast(this@ChangePasswordActivity, message)
                    }
                    UserDbHelper.deleteUserInfo(this@ChangePasswordActivity)
                    //清除Token
                    YgxUtilsKt.setAppToken("", "", "")
                    TUILogin.logout(object : TUICallback() {
                        override fun onSuccess() {
//                            showToast("IM退出登录成功")
                        }

                        override fun onError(errorCode: Int, errorMessage: String?) {
//                            showToast("IM退出登录失败")
                        }
                    })
                    ActivityUtils.finishAllActivities()
                    ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    private fun parseCompanyResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                if (code == "200") {
                    message?.let { message ->
                        showToast(this@ChangePasswordActivity, message)
                    }
                    finish()
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    override fun initConfig() {
        super.initConfig()

        if (mUserInfo != null) {
            val phone = mUserInfo?.phone
            val phoneSub = XmlUtils.parsePhone(phone!!)
            mBinding.tvHint.text = "验证码将发送至手机$phoneSub"
        }
        if (mCompanyInfo != null) {
            val phone = mCompanyInfo?.phone
            val phoneSub = XmlUtils.parsePhone(phone!!)
            mBinding.tvHint.text = "验证码将发送至手机$phoneSub"
        }

    }


    override fun initData() {
        super.initData()

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.iv_eyes_p -> {
                isShowPassWordTop = !isShowPassWordTop
                if (isShowPassWordTop) {
                    mBinding.ivEyesP.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etPassword.transformationMethod = null
                } else {
                    mBinding.ivEyesP.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etPassword.transformationMethod = PasswordTransformationMethod()
                }
                mBinding.etPassword.setSelection(mBinding.etPassword.text.length)
            }

            R.id.iv_eyes -> {
                isShowPassWordBottom = !isShowPassWordBottom
                if (isShowPassWordBottom) {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etPasswordCon.transformationMethod = null
                } else {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etPasswordCon.transformationMethod = PasswordTransformationMethod()
                }
                mBinding.etPasswordCon.setSelection(mBinding.etPasswordCon.text.length)

            }

            R.id.tv_code -> {
                var phone = ""
                if (mUserInfo != null) {
                    phone = mUserInfo?.phone ?: ""
                } else {
                    phone = mCompanyInfo?.phone ?: ""
                }
                showSwipecaptDialog(phone)
            }
        }
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = YgxUtilsKt.sendCode(phone)
                    startLoading()
                    lifecycleScope.launchWhenCreated {
                        this.launch {
                            val result: DataResult<BaseYgxRsp> =
                                myScope.async {
                                    if (mUserInfo != null) {
                                        serviceViewModel.sendCode(
                                            SendCodeBody(
                                                phone,
                                                sendCode
                                            )
                                        )
                                    } else {
                                        serviceViewModel.sendCodeCom(
                                            SendCodeBody(
                                                phone,
                                                sendCode
                                            )
                                        )
                                    }
                                }.await()
                            parseSendCodeResult(result)
                        }
                    }
                }
            })
        swipeCatpchaDialog.show()
    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (code == "200") {
                    if (timer == null) {
                        timer = TimerUnit(mBinding.tvCode)
                    }
                    timer?.startTime()
                    message?.let { message ->
                        showToast(this@ChangePasswordActivity, message)
                    }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }
}